package com.edu.controller;


import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SessionAttributes("loginUser")
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/login")
    public ModelAndView userLogin(User user, Model model){
        int result = userService.userLogin(user);
        ModelAndView mv = new ModelAndView();
        if(result == -1){
            mv.addObject("msg","用户名不存在");
            mv.setViewName("/login.jsp");
        }else if(result == 0){
            mv.addObject("msg","密码错误");
            mv.setViewName("/login.jsp");
        }else if(result == 1){
            model.addAttribute("loginUser",user);
            mv.setViewName("redirect:/book/showBook");
        }
        return mv;
    }
    @PostMapping("/userRegister")
    public ModelAndView userRegister(@Valid User user, BindingResult bindingResult){
        ModelAndView mv = new ModelAndView();
        if (bindingResult.hasErrors()){

            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
            Map<String,String> errors = new HashMap<>();
            for (FieldError fieldError : fieldErrorList) {
                String fieldName = fieldError.getField(); // 获取验证出错的属性的属性名
                String message = fieldError.getDefaultMessage(); // 获取默认的出错的信息提示

                mv.addObject("user",user);
                errors.put(fieldName,message);
                System.out.println(message);
            }

            mv.addObject("errors",errors);
            mv.setViewName("/register.jsp");
        }else {

            int result = userService.userRegister(user);

            if (result == -1) {
                mv.addObject("msg", "用户名重复");
                mv.setViewName("/register.jsp");
            } else if (result == 0) {
                mv.addObject("msg", "注册失败，请稍后再试");
                mv.setViewName("/register.jsp");
            } else {
                mv.setViewName("/login.jsp");
            }
            return mv;
        }
        return mv;
    }



}
